package com.nmcc.app_adherence;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
//import android.widget.Button;
import android.widget.Toast;
//import org.json.*;
//import android.database.sqlite.SQLiteDatabase;
//import android.database.sqlite.SQLiteException;
import java.io.*;
import java.sql.*;
import java.text.SimpleDateFormat;

import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.content.ContentValues;
import android.content.Context;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.os.Environment;
import java.util.UUID;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.widget.Button;
import android.widget.Spinner;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

import android.widget.ArrayAdapter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

import android.text.Editable;
import android.text.TextWatcher;
import android.bluetooth.BluetoothAdapter;
import android.net.Uri;
import java.nio.channels.FileChannel;

public class HouseActivity extends Activity {
	// Button btnShowLocation;
		//The Android's default system path of your application database.
		//try save in in sdcard
		private static String CSV_PATH = "/data/data/com.nmcc.app_Adherence/lib/";
		private static String CSV_NAME = "GPSData.csv";
		private static String CSV_NAME_PERSONS = "Persons.csv";
	   //the record'
		private static String place_name;
		private static String house_number;
		private static String cluster_number;
		private static String house_guid;
		private static String comment;
		private static String household_id;
		private static double longitude;
		private static double latitude;
		private static float accuracy;
		private static double altitude;		
		private static boolean Dontsaverecord=true;
		private static int WasHouseExported=0;
		private int newas1existingas2=1;
		//private static boolean alreadylisteddistricts=false;
	    // GPSTracker class
	    GPSTracker gps;
	    
	    Persons pers;
	    MergeCSV mergcsvClss;
	    MySQLiteHelper sql;
	   // DataBaseHelper myDbHelper;
	    private Spinner spinner1, spinner2;
	    private Button button;
	    private Spinner spnHHResultspn, spnDistrictOrFacility,spnDistrict,spnHFacilitiesspn;
	    //private Spinner spnHouseEditspn;
	   // private ListView lstvwHouseList;
	    
	    @Override
	    protected void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.activity_house);
	        initControls();
	        
	       linkListDistricts();
	  
	        
	             //if i type in housenumber
	        EditText txtHouse_Number = (EditText) findViewById(R.id.txtHouse_Number);
	        txtHouse_Number.addTextChangedListener(new TextWatcher() {
	         public void afterTextChanged(Editable s) {
	        	 //MakeConcetenatedHouseID();
	         }
	         public void beforeTextChanged(CharSequence s, int start, 
	           int count, int after) {
	         }
	         public void onTextChanged(CharSequence s, int start, 
	           int before, int count) {
	        	 TextView mycluster = (TextView) findViewById(R.id.txtCluster_Number);
	        	 if(!mycluster.getText().toString().equals("")){
	        		 String clus = mycluster.getText().toString();
	        	    TextView myOutputBox = (TextView) findViewById(R.id.txthousehold_id);
	          	   //myOutputBox.setText(clus + "-"+s);
	             }
	         }
	        });
	        
	        //if i type in cluster number
	        EditText txtCluster_Number = (EditText) findViewById(R.id.txtCluster_Number);
	        txtCluster_Number.addTextChangedListener(new TextWatcher() {
	         public void afterTextChanged(Editable s) {
	        	 //MakeConcetenatedHouseID();
	         }
	         public void beforeTextChanged(CharSequence s, int start, 
	           int count, int after) {
	         }
	         public void onTextChanged(CharSequence s, int start, 
	           int before, int count) {
	        	 TextView myhouse = (TextView) findViewById(R.id.txtHouse_Number);
	        	 if(!myhouse.getText().toString().equals("")){
	        		 String hs = myhouse.getText().toString();
	        	    TextView myOutputBox = (TextView) findViewById(R.id.txthousehold_id);
	          	   //myOutputBox.setText(s + "-"+hs);
	             }
	         }
	        });
 
	       //the spinner events
	        spnHHResultspn = (Spinner) findViewById(R.id.spnHHResult);
	        spnHHResultspn.setOnItemSelectedListener(new OnItemSelectedListener() {
	            @Override
	            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
	                // your code here
	            	String hhresult =getLast3CharactersOfChoicesAsValue(String.valueOf(spnHHResultspn.getSelectedItem()));
	            	 if (hhresult.equals("_09"))//other specify
		             {
	            		 HideAs1orShowAs2OtherResultControls(1);
		        	 }
			      else 
		            {
			    	     HideAs1orShowAs2OtherResultControls(2);
		        	 }
	            }

	            @Override
	            public void onNothingSelected(AdapterView<?> parentView) {
	                // your code here
	            }

	        });  
	        
	        
	        //spnDistrict);
  			//Spinner spnHFacilitiesspn = (Spinner) findViewById(R.id.spnHealthFacility);
	        
	        //the spinner events
	        spnDistrict = (Spinner) findViewById(R.id.spnDistrict);
	        spnDistrict.setOnItemSelectedListener(new OnItemSelectedListener() {
	            @Override
	            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
	                // your code here
	            	String distrc =String.valueOf(spnDistrict.getSelectedItem());
	            	 //if (hhresult.equals("_09"))//other specify
		             //{
	            		// HideAs1orShowAs2OtherResultControls(1);
		        	// }
			      //else 
		           // {
			    	   //  HideAs1orShowAs2OtherResultControls(2);
		        	// }
	            	 
	            	
	            	ListDistrictsAndFacilities(getApplicationContext(),2,distrc);//facilities
	            	
	            	
	            }

	            @Override
	            public void onNothingSelected(AdapterView<?> parentView) {
	                // your code here
	            }

	        }); 
	        
	        //the spinner events
	        spnHFacilitiesspn = (Spinner) findViewById(R.id.spnHealthFacility);
	        spnHFacilitiesspn.setOnItemSelectedListener(new OnItemSelectedListener() {
	            @Override
	            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
	                // your code here
	            	String selectedFac =getLast3CharactersOfChoicesAsValue(String.valueOf(spnHFacilitiesspn.getSelectedItem()));

	            	final EditText txtCluster_Number=(EditText) findViewById(R.id.txtCluster_Number);       
	            	txtCluster_Number.setText(selectedFac.trim());
	  			     
	            	//ListDistrictsAndFacilities(getApplicationContext(),2,distrc);//facilities
	            }

	            @Override
	            public void onNothingSelected(AdapterView<?> parentView) {
	                // your code here
	            }

	        }); 
	        
	        //alreadylisteddistricts=true;
	    }
	 
	    private void initControls()
	    {
	        final EditText txtHouse_Number=(EditText) findViewById(R.id.txtHouse_Number);       
	        final EditText txtCluster_Number=(EditText) findViewById(R.id.txtCluster_Number);       

	        final EditText txtPlace_Name=(EditText) findViewById(R.id.txtPlace_Name);       
	        final EditText txtComment=(EditText) findViewById(R.id.txtComment);       
	        
	        final EditText txtLongitude=(EditText) findViewById(R.id.txtLongitude);       

	        final EditText txtLatitude=(EditText) findViewById(R.id.txtLatitude);       
	        final EditText txthousehold_id=(EditText) findViewById(R.id.txthousehold_id);       
	        addItemsOnSpinnerHHResult();
	        //addItemsOnSpinnerHouseToEdit();
	        
	        UUID uuid = UUID.randomUUID();
	     	txthousehold_id.setText("uuid:" + uuid.toString());
	     	
	     	
	        HideAs1orShowAs2OtherResultControls(2);
	        
	        
	        
    
	    FillHouseDetails();
	    
	    
	        HideSomeControls();
	        

	    }
	    
	    private void FillHouseDetails(){
	    	
		MySQLiteHelper db = new MySQLiteHelper(this);
	    	
	    	//String hs = db.GetSetting(1);//0 for a new serach
			//String cl = db.GetSetting(2);//0 for a new search
			String getSelectedHouseID = db.GetSetting(3);//has ui8928uiw-gew787 for a new search
			 
			if (getSelectedHouseID.equals(""))//new house
            {
				newas1existingas2=1;
	    		return;
            }
			else {
				newas1existingas2=2;//existing house
			}

			       //fill the data
			        final EditText txtHouse_Number=(EditText) findViewById(R.id.txtHouse_Number);       
			        final EditText txtCluster_Number=(EditText) findViewById(R.id.txtCluster_Number);       

			        final EditText txtPlace_Name=(EditText) findViewById(R.id.txtPlace_Name);       
			        final EditText txtComment=(EditText) findViewById(R.id.txtComment);       
			        
			        final EditText txtLongitude=(EditText) findViewById(R.id.txtLongitude);       

			        final EditText txtLatitude=(EditText) findViewById(R.id.txtLatitude);       
			        final EditText txthousehold_id=(EditText) findViewById(R.id.txthousehold_id); 
			       //RetHN1Clust2HouseID3Lon4Lat5HDOP6housid7Plac8HHResult9HHResultOther10HHResultLabel11comment12WasExported13
			        spnHHResultspn = (Spinner) findViewById(R.id.spnHHResult);
		            final EditText txtHHResult1=(EditText) findViewById(R.id.txtOtherSpecifyHHResult); 
		               
			        
			        
			        txtHouse_Number.setText(db.GetHouseDetailsOfSelectedHouse(getSelectedHouseID, 1));
			        txtCluster_Number.setText(db.GetHouseDetailsOfSelectedHouse(getSelectedHouseID, 2));
			        txtPlace_Name.setText(db.GetHouseDetailsOfSelectedHouse(getSelectedHouseID, 8));
			        txtComment.setText(db.GetHouseDetailsOfSelectedHouse(getSelectedHouseID, 12));
			        txtLongitude.setText(db.GetHouseDetailsOfSelectedHouse(getSelectedHouseID, 4));
			        txtLatitude.setText(db.GetHouseDetailsOfSelectedHouse(getSelectedHouseID, 5));
			        txthousehold_id.setText(db.GetHouseDetailsOfSelectedHouse(getSelectedHouseID, 7));
			        house_guid=db.GetHouseDetailsOfSelectedHouse(getSelectedHouseID, 3);
			        
		
			       //WasHouseExported=Integer.parseInt(db.GetHouseDetailsOfSelectedHouse(getSelectedHouseID, 13));
	    		    //was exported field WasExported;
			        txtHHResult1.setText(db.GetHouseDetailsOfSelectedHouse(getSelectedHouseID, 10));
		               
		            String hhresult =getLast3CharactersOfChoicesAsValue(String.valueOf(spnHHResultspn.getSelectedItem()));
		            
		            int spinnerposition=getIndex(hhresult);
		            spnHHResultspn.setSelection(spinnerposition);//(db.GetHouseDetailsOfSelectedHouse(getSelectedHouseID, 10));
       
			        
            //}
	    	
	    }
	    
	    private int getIndex(String textvalue){
	    	if (textvalue.equals("_00"))
            {
	    		return 1;
            }

	    	else if (textvalue.equals("_10"))
            {
	    		return 2;
            }
	    	else if (textvalue.equals("_02"))
            {
	    		return 3;
            }
	    	else if (textvalue.equals("_03"))
            {
	    		return 4;
            }	    
	    	
	    	else if (textvalue.equals("_04"))
            {
	    		return 5;
            }

	    	else if (textvalue.equals("_05"))
            {
	    		return 6;
            }
	    	else if (textvalue.equals("_06"))
            {
	    		return 7;
            }
	    	else if (textvalue.equals("_07"))
            {
	    		return 8;
            }
	    	else if (textvalue.equals("_08"))
            {
	    		return 9;
            }

	    	else if (textvalue.equals("_09"))
            {
	    		return 10;
            }
	    	
	    	else
            {
	    		return 1;
            }
	    	
	   }
	    
	    
	    private void HideAs1orShowAs2OtherResultControls(int showAs1HideAs2){
		    	if (showAs1HideAs2==1)
	            {
		    		final EditText txtHHResult5=(EditText) findViewById(R.id.txtOtherSpecifyHHResult); 
			        final TextView lblHHResult5=(TextView) findViewById(R.id.lblOtherSpecifyHHResult);
			        txtHHResult5.setVisibility(View.VISIBLE);
			        lblHHResult5.setVisibility(View.VISIBLE);
		
		       	 }
			     else if (showAs1HideAs2==2)
		           {
			    	 final EditText txtHHResult5=(EditText) findViewById(R.id.txtOtherSpecifyHHResult); 
				        final TextView lblHHResult5=(TextView) findViewById(R.id.lblOtherSpecifyHHResult);
				        txtHHResult5.setVisibility(View.GONE);
				        lblHHResult5.setVisibility(View.GONE);
		
		       	 }
	    	
	    }

	    private void HideSomeControls(){
           
            final EditText txthousehold_id=(EditText) findViewById(R.id.txthousehold_id);       
            final TextView lblhousehold_id=(TextView) findViewById(R.id.lblhousehold_id); 
            
            txthousehold_id.setVisibility(View.GONE);
            lblhousehold_id.setVisibility(View.GONE);


            //final EditText txtClusterNumber=(EditText) findViewById(R.id.txtCluster_Number);       
            //final TextView lblClusterNumber=(TextView) findViewById(R.id.lblCluster_Number); 
            
            //txtClusterNumber.setVisibility(View.GONE);
            //lblClusterNumber.setVisibility(View.GONE);
    	
    }
	    // add items into spinner dynamically
	    public void addItemsOnSpinnerHHResult() {
	    	spnHHResultspn = (Spinner) findViewById(R.id.spnHHResult);
	      List list = new ArrayList();
	      list.add("Choose a result" + "                                    " + "_00");
	      list.add("HOUSEHOLD PRESENT" + "                                  " + "_10");
	      //list.add("COMPLETED" + "                                                 " + "_01");
	      list.add("NO HOUSEHOLD MEMBER AT HOME OR NO COMPETENT RESPONDENT AT HOME AT TIME OF VISIT" + "                                         " + "_02");
	      list.add("ENTIRE HOUSEHOLD ABSENT FOR EXTENDED PERIOD OF TIME" + "                                      " + "_03");
	      list.add("POSTPONED" + "                        " + "_04");
	      list.add("REFUSED" + "                                           " + "_05");
	      list.add("DWELLING VACANT OR ADDRESS NOT A DWELLING" + "                                               " + "_06");
	      list.add("DWELLING DESTROYED" + "                                        " + "_07");      
	      list.add("DWELLING NOT FOUND" + "                                    " + "_08");
	      list.add("OTHER,(SPECIFY)" + "                                       " + "_09");
	 
	      ArrayAdapter dataAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, list);
	      dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	      spnHHResultspn.setAdapter(dataAdapter);
	    }
	    
	   
	  //  @Override
	   // public boolean onCreateOptionsMenu(Menu menu) {
	        // Inflate the menu; this adds items to the action bar if it is present.
	       // getMenuInflater().inflate(R.menu.activity_main, menu);
	      //  return true;
	    //}
	   // @Override
	   // public void onCreate(Bundle savedInstanceState) {
	     //   super.onCreate(savedInstanceState);
	       // setContentView(R.layout.activity_main);
	         
	       //btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
	         
	        // show location button click event
	        //btnShowLocation.setOnClickListener(new View.OnClickListener() {
	                  
	                //@Override
	            public void GetGPSLinker(View view) {       
	                // create class object
	                gps = new GPSTracker(HouseActivity.this);
	                // check if GPS enabled   
	                //Dontsaverecord=false;
	                
	                if(gps.canGetLocation()){
	                   
	                   latitude = gps.getLatitude();
	                   longitude = gps.getLongitude();
	                   
	                   altitude = gps.getAltitude();
	                   accuracy = gps.getAccuracy();
	                     
	                    // \n is for new line
	                    Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude + "\nAltitude: " + altitude + "\nAccuracy: " + accuracy, Toast.LENGTH_LONG).show();   
	                
	                    final EditText txtLongitude=(EditText) findViewById(R.id.txtLongitude);       
	                    final EditText txtLatitude=(EditText) findViewById(R.id.txtLatitude);       

	                    txtLongitude.setText(String.valueOf(longitude));
	                    txtLatitude.setText(String.valueOf(latitude));
	                   
	                    
	                    Button btnshowlocation = (Button) findViewById(R.id.btnShowLocation);
	                    
	                    if (accuracy < 100){
	                    	
	                    	if (accuracy < 25){
	                    	    btnshowlocation.setBackgroundColor(Color.GREEN);
	                    	}
	                    	else {//greater than 25 not very accurate
	                    		btnshowlocation.setBackgroundColor(Color.YELLOW);; //TAKE yelllow
		                    	
		                    }
	                    }
	                    else {//greater than 100 not very accurate
	                    	btnshowlocation.setBackgroundColor(Color.RED);; //TAKE red colour
	                    }
	                    
	                    //give values
	                    //place_name= txtPlace_Name.getText().toString();
	                	//house_number=txtHouse_Number.getText().toString();
	                	//cluster_number=txtCluster_Number.getText().toString();
	                	//comment=txtComment.getText().toString();
	                    
	                	//UUID uuid = UUID.randomUUID();
	                	//house_guid = uuid.toString();
	                   
	                    
	                	//if (!Dontsaverecord)
	        			//{
	                   // SaveIntoCSVLinker();
	                     //generateCsvFile(CSV_NAME);
	        			//}
	                    
	                }else{
	                    // can't get location
	                    // GPS or Network is not enabled
	                    // Ask user to enable GPS/network in settings
	                    gps.showSettingsAlert();
	                }
	                 
	            }
	            
	            
	            // CREATE TABLE IF NOT EXISTS
	           public void SaveIntoDatabase(View view)
	            {
	        	   //UUID uuid = UUID.randomUUID();
	   			//txtPersonID.setText(uuid.toString());
	        	   
	        	   //EntriesAllFilledIn
	        	   if (!EntriesAllFilledIn()){
	        		   //Toast.makeText(getApplicationContext(), "Empty BOX! Please complete all the entries before saving. If no GPS points available, enter, 0 in latitude and longitude.", Toast.LENGTH_LONG).show(); 
	        		   Toast.makeText(getApplicationContext(), "Empty BOX! Please complete all the entries before saving. If no GPS points available, enter, 0 in latitude and longitude.", 5000).show();
	        		   return;
	        	   }
	        	   
	        	   
	               final EditText txtLongitude=(EditText) findViewById(R.id.txtLongitude);       
	               final EditText txtLatitude=(EditText) findViewById(R.id.txtLatitude);       
	               final EditText txtPlace_Name=(EditText) findViewById(R.id.txtPlace_Name);       
	               final EditText txtHouse_Number=(EditText) findViewById(R.id.txtHouse_Number);       
	               final EditText txtCluster_Number=(EditText) findViewById(R.id.txtCluster_Number);       
	               final EditText txtComment=(EditText) findViewById(R.id.txtComment);       
	               final EditText txthousehold_id=(EditText) findViewById(R.id.txthousehold_id);       
	  
	               //final EditText txthhresultother=(EditText) findViewById(R.id.txtHHResultOther);       
	         	  
	               spnHHResultspn = (Spinner) findViewById(R.id.spnHHResult);
	               final EditText txtHHResult1=(EditText) findViewById(R.id.txtOtherSpecifyHHResult); 
	               
	               String hhresult =getLast3CharactersOfChoicesAsValue(String.valueOf(spnHHResultspn.getSelectedItem()));
	        	   
	               //give values
	              String hhresultOther= txtHHResult1.getText().toString();
	              
	            place_name= txtPlace_Name.getText().toString();
	           	house_number=txtHouse_Number.getText().toString();
	           	cluster_number=txtCluster_Number.getText().toString();
	           	//cluster_number="009";
	           	comment=txtComment.getText().toString();
		   	    household_id=txthousehold_id.getText().toString();//need to find value

		   	    
 
	     	
	        	   //database operations
	               MySQLiteHelper db = new MySQLiteHelper(this);
	               // add Books
	               
	               if (newas1existingas2==1){
		               //db.DropAllTables();
					   	 UUID uuid = UUID.randomUUID();
				     	house_guid = "uuid:" + uuid.toString();
				     	
			               //change this
			               household_id = house_guid;
			        }
	               else {//existing house
	            	  // house_guid = ; donothing its gotten when seraching
	            	   //household_id = house_guid; donothing is gotten on top
	            	   
	               }
	               	
	               
	               String datenow=db.getNow();
	               
	               
	               
	             db.addHouseGPS(newas1existingas2,Integer.parseInt(house_number),Integer.parseInt(cluster_number),house_guid,longitude, latitude,accuracy,household_id,  place_name,hhresult, hhresultOther, GetHHResultLabel(hhresult), comment,datenow);
	        	 db.addSetting(Integer.parseInt(house_number), Integer.parseInt(cluster_number), house_guid,"","");
	        	   
	        	 // return;
	        	  
	        	 //before clearing add the record to odk survey
	        	 if (newas1existingas2==1){
	        		 //ExportGPSDataTakeToODKDirectNewMethod(view, newas1existingas2, comment, place_name, house_guid);
	        	 }

		          clearboxes();
	        	   
	        	  if(hhresult.equals("_10")){//household is present
	        		  Toast.makeText(getApplicationContext(), "House successfully added. You now have to add members to this house.", 10000).show();
		               Go_To_MainMenu_Linker(view);
              
		          }
	              else {
	        		  Toast.makeText(getApplicationContext(), "House added. No members of this house will be entered in this program.", 10000).show();
	              
	        		  final Context context = this;
	           	   Intent intent = new Intent(context, HouseActivity.class);
	                  finish();
	        		  
	              }
	        	  
	        	 
	            }
	          
	  		 private String getLast3CharactersOfChoicesAsValue(String gnstr) {
				 //get _01 in say 'Head    _01'	 	   last3 = str.substring(str.length() - 3);
		 	       //String relat=String.valueOf(spnRelations1.getSelectedItem());
		 	       //check if its first option 'Select Gender.....  _00', then return null
		 	      
				 String lastcharacterUseForCompare = "0";
				 String Extractedlastcharacter = gnstr.substring(gnstr.length() - 1);
				 
				 if (lastcharacterUseForCompare==Extractedlastcharacter){
		 	    	   return null;
		 	      } else {
		 	    		   return gnstr.substring(gnstr.length() - 3);
		 	    		  
		 	       }
		 	    	   
			 }         

	  		public String GetHHResultLabel(String HHResultValue){
		       	 String valueToReturn;
		       	 //txtName.getText().toString().equals("")
					     if (HHResultValue.equals("_00"))
				             {
				        	 valueToReturn= "NOT SELECTED ANY OPTION";
			
				        	 }
					     else if (HHResultValue.equals("_01"))
				            {
				        	 valueToReturn= "COMPLETED";

				        	 }
				         else if (HHResultValue.equals("_02"))
				        	 {
				        	 valueToReturn= "NO HOUSEHOLD MEMBER AT HOME OR NO COMPETENT RESPONDENT AT HOME AT TIME OF VISIT";
				        	 } 
				         else if (HHResultValue.equals("_03"))
				             {
				        	 valueToReturn= "ENTIRE HOUSEHOLD ABSENT FOR EXTENDED PERIOD OF TIME";
				        	 } 
				         else if (HHResultValue.equals("_04")) 
			                 {
			        	     valueToReturn= "POSTPONED";
			        	     } 
				         else if (HHResultValue.equals("_05"))
			                 {
			        	     valueToReturn= "REFUSED";
			        	     }
				         else if (HHResultValue.equals("_06"))
		                    {
		       	            valueToReturn= "DWELLING VACANT OR ADDRESS NOT A DWELLING";
		       	            } 
				         
				         else if (HHResultValue.equals("_07"))
		                    {
		       	            valueToReturn= "DWELLING DESTROYED";
		       	            } 
				         
				         else if (HHResultValue.equals("_08"))
		                    {
		       	            valueToReturn= "DWELLING NOT FOUND";
		       	            } 
				         
				         else if (HHResultValue.equals("_09"))
		                    {
		       	            valueToReturn= "OTHER,(SPECIFY)";
		       	            } 
 				         //HOUSEHOLD PRESENT
				         else if (HHResultValue.equals("_10"))
		                    {
		       	            valueToReturn= "HOUSEHOLD PRESENT";
		       	            } 
				         
				         else 
				             {
				        	 throw new IllegalArgumentException();
				        	 }
			         return valueToReturn;

			         //return null;
			 }
		 
	  		
	  		public void EditSelectedHouse(View view)
            {
        	   

            }
	           
	           public void TransferToCSV(View view)
	           {
	       	   Dontsaverecord=false;
	       	// SaveIntoCSVLinker();
	             // generateCsvFile(CSV_NAME);
	       	GetGPSLinker(view);
	       	   Dontsaverecord=true;
	       	   
	           }
	           
	            
	         
	           public void Go_To_MainMenu_Linker(View view)
	            {
	        	   final Context context1 = this;
	                  //give values
	           	   Intent intent1 = new Intent(context1, HouseActivity.class);
	                  finish();
	        	   
	        	   //'navigate to another screen'
	        	   final Context context = this;
	               //give values
	        	   Intent intent = new Intent(context, HouseDetailsActivity.class);
	        	   //intent.putExtra("cluster","22");
	        	    startActivity(intent);
	            }
	           
	            // Go to another screen
	           public void Go_To_Persons_Linker(View view)
	            {
	        	   //'navigate to another screen'
	        	   final Context context = this;
	              //final EditText txtHouse_Number=(EditText) findViewById(R.id.txtHouse_Number);       
	             // final EditText txtCluster_Number=(EditText) findViewById(R.id.txtCluster_Number);       

	              //final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
	              //Set housenumber and clusternumber in global/application context
	              //globalVariable.setHouseNumber(txtHouse_Number.getText().toString());
	              //globalVariable.setClusterNumber(txtCluster_Number.getText().toString());

	               //give values
	        	   Intent intent = new Intent(context, Persons.class);
	        	   //intent.putExtra("cluster","22");
	        	    startActivity(intent);
	        	    
	        	    //pass the variables
	        	   //pers.GetVariables(house_number, cluster_number);
	            }
	          //@Override
	                   //});
	    //}
	           public boolean EntriesAllFilledIn(){
	        	   //boolean YesCompleted;
	        	   
	               final EditText txtLongitude=(EditText) findViewById(R.id.txtLongitude);       
	               final EditText txtLatitude=(EditText) findViewById(R.id.txtLatitude);       
	               final EditText txtPlace_Name=(EditText) findViewById(R.id.txtPlace_Name);       
	               final EditText txtHouse_Number=(EditText) findViewById(R.id.txtHouse_Number);       
	               final EditText txtCluster_Number=(EditText) findViewById(R.id.txtCluster_Number);       
	               final EditText txtComment=(EditText) findViewById(R.id.txtComment);       
	               final EditText txthousehold_id=(EditText) findViewById(R.id.txthousehold_id);       
	  
	               spnHHResultspn = (Spinner) findViewById(R.id.spnHHResult);
	               //final EditText txtHHResult1=(EditText) findViewById(R.id.txtOtherSpecifyHHResult); 
	               
	               String hhresult =getLast3CharactersOfChoicesAsValue(String.valueOf(spnHHResultspn.getSelectedItem()));
	        	   
	               if(txtLongitude.getText().toString().equals("")){
	                   return false;
	               }
	               
	               if(txtLatitude.getText().toString().equals("")){
	                   return false;
	               }
	               
	               if(txtPlace_Name.getText().toString().equals("")){
	                   return false;
	               }
	               
	               if(txtHouse_Number.getText().toString().equals("")){
	                   return false;
	               }
	               
	               if(txtComment.getText().toString().equals("")){
	                   return false;
	               }
	               
	               if(txtCluster_Number.getText().toString().equals("")){
	                   return false;
	               }
	               
	               if(txthousehold_id.getText().toString().equals("")){
	                   return false;
	               }
	               
	               if(hhresult.equals("_00")){
	                   return false;
	               }
	               //else return true
	               return true;
	           }
	     
	           
	           public void clearboxes(){

	   		   	
	               final EditText txtLongitude=(EditText) findViewById(R.id.txtLongitude);       
	               final EditText txtLatitude=(EditText) findViewById(R.id.txtLatitude);       
	               final EditText txtPlace_Name=(EditText) findViewById(R.id.txtPlace_Name);       
	               final EditText txtHouse_Number=(EditText) findViewById(R.id.txtHouse_Number);       
	               final EditText txtCluster_Number=(EditText) findViewById(R.id.txtCluster_Number);       
	               final EditText txtComment=(EditText) findViewById(R.id.txtComment);       
	               final EditText txthousehold_id=(EditText) findViewById(R.id.txthousehold_id);       

	               txtLongitude.setText("");    
	               txtLatitude.setText("");
	               //txtPlace_Name.setText("");
	               txtHouse_Number.setText("");
	               //txtCluster_Number.setText("");             
	               txtComment.setText(""); 
	               
	               //"uuid:" + uuid.toString()
	               UUID uuid = UUID.randomUUID();
	               txthousehold_id.setText("uuid:" + uuid.toString());  
			   	
		 	 }
	           
	  		 public void MakeConcetenatedHouseID() {
	             final EditText txtHouse_Number=(EditText) findViewById(R.id.txtHouse_Number);       
	             final EditText txtCluster_Number=(EditText) findViewById(R.id.txtCluster_Number);       
	                  
	             final EditText txthousehold_id=(EditText) findViewById(R.id.txthousehold_id);       

	             if(txtHouse_Number.getText().toString().equals("")){
	                 return;
	             }
	             
	             if(txtCluster_Number.getText().toString().equals("")){
	                 return;
	             }
	             
	             //else, since they are not blank
	             txthousehold_id.setText(txtCluster_Number.getText().toString() + "-" + txtHouse_Number.getText().toString()); 
	   	    	   
			 }
  	   
	  		 
	  		public void ListDistrictsAndFacilities(Context context, int listDistrictsAs1FacilitiesAs2, String givenDistrict) {
	  			Spinner spnDistrictsspn = (Spinner) findViewById(R.id.spnDistrict);
	  			Spinner spnHFacilitiesspn = (Spinner) findViewById(R.id.spnHealthFacility);
	  				
	  			    if (listDistrictsAs1FacilitiesAs2==1){//to avoid crushing when close this form
	  						if (spnDistrictsspn.getCount()>0){//already has items
	  							return;
			  			    }
	
	  				}

			  		
	  			List list = new ArrayList();
	  			
	  			int counter=0;
	  			
	  			//<string name="lblDistrict">District</string>
	  			//<string name="spnDistrict">District</string>
	  			//<string name="select_District">Select District</string>
	  		   // <string name="lblHealthFacility">Health Facility</string>
	  			//<string name="spnHealthFacility">Health Facility</string>
	  			//<string name="select_HealthFacility">Select Health Facility</string>
	  			
	  			String sdcard = Environment.getExternalStorageDirectory().toString();
	  			//String csvFile = "/Users/mkyong/Downloads/GeoIPCountryWhois.csv";
	  			//sdcard+ "/bluetooth/" + CSVfilenameGPS
	  			//InputStream is = getAssets().open("drop down lists for travel questions.csv")
	  			//tables/household_member_travel/forms/travel
	  			
	  			String csvFile = sdcard + "/opendatakit/survey/tables/household_member_travel/forms/travel/districts.csv";
	  			
	  			BufferedReader br = null;
	  			String line = "";
	  			String cvsSplitBy = ",";
	  		 
	  			try {
	  		 
	  				br = new BufferedReader(new FileReader(csvFile));
	  				while ((line = br.readLine()) != null) {
	  						
	  					
	  					
	  				        // use comma as separator
	  					String[] distFac = line.split(cvsSplitBy);
	  		 
	  					//System.out.println("Country [code= " + country[4] 
	  		                              //   + " , name=" + country[5] + "]");
	  					
	  					//String s=;
	  					
	  					if (counter > 0){
	  						//no printing the headings at first time
		  					if (listDistrictsAs1FacilitiesAs2==1){
		  						//mySpinner.setSelection();
		  						//if (!stringExistsInSpinner(spnDistrictsspn, distFac[1])){
		  						if (!list.contains(distFac[1])){
		  							list.add(distFac[1]);
		  						}

		  					}
		  					else if (listDistrictsAs1FacilitiesAs2==2){

		  						if (givenDistrict.equals(distFac[1])){
		  							list.add( distFac[2] + "          " + distFac[0]);
		  						
		  						}
		  								
		  					}	  						
	  					}
	  					//list districts, no duplicates


	  					
	  					//list facilities, no duplicates
	  					
	  					
	  					
	  					counter=counter+1;
	  					
	  			
	  				}
	  				
  	  		      ArrayAdapter dataAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, list);
	  		      dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);	  				
	  				
			  				
		  				if (listDistrictsAs1FacilitiesAs2==1){
		  					spnDistrictsspn.setAdapter(dataAdapter);
						}
						else if (listDistrictsAs1FacilitiesAs2==2){
							spnHFacilitiesspn.setAdapter(dataAdapter);
						}

						
	  		      
	  		      
	  			} catch (FileNotFoundException e) {
	  				e.printStackTrace();
	  			} catch (IOException e) {
	  				e.printStackTrace();
	  			} finally {
	  				if (br != null) {
	  					try {
	  						br.close();
	  					} catch (IOException e) {
	  						e.printStackTrace();
	  					}
	  				}
	  			}
	  		 
	  			System.out.println("Done");
	  		  }	 

	  		public void linkListDistricts(){
	  			//if (!alreadylisteddistricts){
	  				ListDistrictsAndFacilities(getApplicationContext(),1,"");//districts
	  			//}
	  			
	  			//ListDistrictsAndFacilities(getApplicationContext(),2);//facilities
	  		}
	  		
	  		
	  		public boolean itemExistsInSpinner(Spinner spinnerS, String itemToCheck){
	  			int numberofRecs=70;
	  			boolean result=false;
	  			String extractedString;

	  		     // Files: Input
	  	        for (int i = 0; i <= numberofRecs; i++) {
	  
	  	        	extractedString = spinnerS.getItemAtPosition(i).toString();
	  		        		
	  		        		if (itemToCheck.equals(extractedString)){
	  		        			result=true;
	  		        		}
      		
	  	        }
	  	        
	  	        return result;
	  	        
	  		}
	  			  		
	
	  		 private boolean stringExistsInSpinner(Spinner spinner, String myString){
	  		 
	  		  //int index = 0;
	  		 
	  		  for (int i=0;i<spinner.getCount();i++){
	  		   if (spinner.getItemAtPosition(i).equals(myString)){
	  			   
	  		    return true;
	  		   }
	  		   
	  		  }
	  		  return false;
	  		 }
	  		
	
	  		 
	  		 
	  		 
	  		 
	  		 public void ExportGPSDataTakeToODKDirectNewMethod(View view, int newAs1ExistingAs2, String comment, String placename, String newhouseguid ){
	  			 SQLiteDatabase db;
	  			 
	  			String dir = Environment.getExternalStorageDirectory().getPath();
	  			File dbfile = new File(dir+"/opendatakit/survey/metadata/webDb/http_localhost_8635/0000000000000001.db"); 
	  			db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
	  			
	  				//UUID uuid = UUID.randomUUID();
	  				//String newhouseguid=uuid.toString();

	  				if (newAs1ExistingAs2==2){
	  			        	 // db.execSQL("UPDATE GPSData SET " +
	  			      		//"HouseNumber=" + HouseNumber + 
	  			      		//"', comment='" + comment + "' WHERE HouseID='" + HouseID + "'");

	  		               }
	  			          else if (newAs1ExistingAs2==1){
	  	                      //2014-10-06-10.57.45.666000000
	  			        	  //2014-10-05T22:53:34.293000000
	  			        	  
	  			        	  //2014-10-06T11:08:19.894000000
	  			        	  //2014-10-06T11:18:21.942000000
	  			        	Timestamp timestamp = new Timestamp(System.currentTimeMillis());
	  			          SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.");
	  			          //yyyy-MM-dd'T'HH:mm:ssZ
	  			          
	  			          format.setTimeZone(TimeZone.getDefault()); // Set the TimeZone to whatever you are expecting.
	  			          String timestampedDate = format.format(timestamp) + String.format("%09d", timestamp.getNanos());
  			          
	  			        	  
	  			        	  
	  			        	  ContentValues cv = new ContentValues();
	  			        	  cv.put("_id", "uuid:"+ newhouseguid);
	  			        	 cv.put("_sync_state", "new_row"); 
	  			        	  cv.put("_form_id", "household_new"); 
	  			        	  cv.put("_locale", "default"); 
	  			        	 cv.put("_savepoint_timestamp", timestampedDate); //redo time need .89000000000
	  			        	 cv.put("_savepoint_creator", "anonymous"); 
	  			        	 
	  			        	  //housedetails
	  			        	  cv.put("place_name_selected", placename); 
	  			        	  cv.put("household_id", newhouseguid); 
	  			        	  cv.put("comment", comment); 
	  			        	  cv.put("household_id_selected", newhouseguid);
	  			        	  cv.put("comment_selected", comment);

	  			        	  
	  			        	  db.insert("household", null, cv);
	  			        	  //db.close();
	  			          }

	  			          db.close(); 
	  		
	  		}   

	  		 
	  	
}
